package com.yj.string;

import java.util.Stack;

/**
 * 给出一个仅包含字符'(',')','{','}','['和']',的字符串，判断给出的字符串是否是合法的括号序列
 * 括号必须以正确的顺序关闭，"()"和"()[]{}"都是合法的括号序列，但"(]"和"([)]"不合法。
 */
public class Solution01 {


    //<editor-fold desc="括号序列">
    public static void main(String[] args) {

        boolean isValid = isValid1("()");
        System.out.println(isValid);
        boolean isValid2 = isValid2("({})");
        System.out.println(isValid2);

    }

    private static boolean isValid2(String s) {
        char[] chars = s.toCharArray();
        Stack<Character>stack = new Stack();
        for (char aChar : chars) {
            if (aChar == '('){
                stack.push(')');
            }else if (aChar == '{'){
                stack.push('}');
            }else if (aChar == '['){
                stack.push(']');
            }else if (stack.isEmpty() || stack.pop() != aChar ){
                return false;
            }
        }
        return stack.isEmpty();
    }

    private static boolean isValid1(String s) {

        boolean flag = true;
        while (flag){
            int len = s.length();
            s = s.replace("()", "");
            s = s.replace("[]", "");
            s = s.replace("{}", "");
            if (len == s.length()){
                flag = false;
            }
        }
        return s.length() == 0;
    }
    //</editor-fold>

}
